package com.xinyue.game.client.network;

import com.xinyue.network.codec.GameMessageContext;
import com.xinyue.network.codec.GameMessageHeader;
import com.xinyue.network.hamdlermapping.GameChannelContext;
import com.xinyue.network.hamdlermapping.GameHandlerMappingService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 王广帅
 * @date 2021年01月28日 1:08 上午
 */
public class LogicHandler extends ChannelInboundHandlerAdapter {
    private Logger logger = LoggerFactory.getLogger(EncodeHandler.class);

    private GameHandlerMappingService gameHandlerMappingService;

    public LogicHandler(GameHandlerMappingService gameHandlerMappingService) {
        this.gameHandlerMappingService = gameHandlerMappingService;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        GameMessageContext gameMessageContext = (GameMessageContext) msg;
        GameMessageHeader header = gameMessageContext.getHeader();
        GameChannelContext channelContext = new GameChannelContext(ctx, gameMessageContext);
        gameHandlerMappingService.callMethod(channelContext, header.getMessageId(), header.getMessageType(), gameMessageContext.getGameMessage());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("读取服务器数据失败", cause);
    }
}
